<?php
declare (strict_types=1);

namespace app\common\listener;

use app\common\facade\Jpush;
use app\common\model\OrderProduct;
use app\common\model\User;
use app\common\model\UserNotify;
use app\common\tool\account\Account;

class GiveRedCoin
{
    public function handle($order)
    {
        try {
            if($red_coin = OrderProduct::where('order_id', $order->id)->sum('give_red_coin')){
                Account::getInstance()->basics($order->uid, 'red_coin', $red_coin, '赠送积分', '+')->setOrder($order->id)->createNormal();

                $user = User::find($order->uid);
                $content = "入账积分金额：{$red_coin}";
                $parameter = ['event_type'=>1003,'sub_event_type'=>1100];
                $extra = ['extras'=>['parameter'=>json_encode($parameter)]];

                Jpush::sendSingleNotify($user->registration_id, $content, $extra, $user->id);

                UserNotify::create([
                    'uid' => $user->id,
                    'type' => 11,
                    'title' => '积分到账',
                    'content' => $content
                ]);
            }

            return true;
        } catch (\Exception $e) {
            throw new \Exception($e->getMessage(), -1);
        }
    }


}